package repo

import (
	"time"

	"gorm.io/gorm"

	"coupons/repo/model"
)

// VoucherRepo 优惠券数据库操作
type VoucherRepo struct {
	db *gorm.DB
}

// NewVoucherRepo 创建优惠券仓库实例
func NewVoucherRepo(db *gorm.DB) *VoucherRepo {
	return &VoucherRepo{
		db: db,
	}
}

// GetVoucherByVoucherId 根据voucherId获取优惠券
func (r *VoucherRepo) GetVoucherByVoucherId(voucherId string) (*model.SeckillVoucher, error) {
	var voucher model.SeckillVoucher
	err := r.db.Where("voucher_id = ?", voucherId).First(&voucher).Error
	if err != nil {
		return nil, err
	}
	return &voucher, nil
}

// GetVoucherList 获取优惠券列表
func (r *VoucherRepo) GetVoucherList(offset, limit int) ([]model.SeckillVoucher, int64, error) {
	var vouchers []model.SeckillVoucher
	var total int64

	// 获取总数
	if err := r.db.Model(&model.SeckillVoucher{}).Count(&total).Error; err != nil {
		return nil, 0, err
	}

	// 获取分页数据
	if err := r.db.Offset(offset).Limit(limit).Find(&vouchers).Error; err != nil {
		return nil, 0, err
	}

	return vouchers, total, nil
}

// GetUpcomingVouchers 获取即将开始的优惠券
func (r *VoucherRepo) GetUpcomingVouchers(now time.Time) ([]model.SeckillVoucher, error) {
	var vouchers []model.SeckillVoucher
	err := r.db.Where(
		"begin_time BETWEEN ? AND ?",
		now,
		now.Add(time.Hour*100000),
	).Find(&vouchers).Error

	if err != nil {
		return nil, err
	}
	return vouchers, nil
}

// MarkAsNotified 标记优惠券为已通知
func (r *VoucherRepo) MarkAsNotified(voucherId string) error {
	return r.db.Model(&model.SeckillVoucher{}).Where("voucher_id = ?", voucherId).Update("notified", 1).Error
}
